package com.clouddot.baipai.ui.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.clouddot.baipai.infrastructure.environment.initial.InitialAppContext;
import com.clouddot.baipai.infrastructure.environment.initial.InitialAppUpdate;
import com.clouddot.baipai.infrastructure.environment.initial.InitialHardware;
import com.clouddot.baipai.model.beam.bindBanPai.bindBanPaiResponse;
import com.clouddot.baipai.model.beam.getAllClass.allclassInfo;
import com.clouddot.baipai.model.beam.getAllClass.getAllClassResponse;
import com.clouddot.baipai.ui.util.Ftp.AnalyzeXMLUtil;
import com.clouddot.baipai.ui.util.SlideSwitch;
import com.clouddot.baipai.ui.util.ToastUtil;
import com.clouddot.baipai.ui.util.dropListView.dropDownListView;
import com.clouddot.baipai.model.beam.getVersionInfo.XMLBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wxy on 2018/4/10.
 */

public class A_Set1Fragment extends BaseFragment implements View.OnClickListener{

    private View view;
    private LinearLayout isEsit, bind;
    private dropDownListView spinner;
    private EditText editText,url,scanVerify,time;
    private TextView textView;
    private ConstraintLayout openScantrue;
    private SlideSwitch openScanSlideSwitch;
    private Handler handler = new Handler();
    private List<allclassInfo> list = new ArrayList<allclassInfo>();
    private Activity activity;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return view;
    }

    @Override
    protected void setContentView() {
        super.setContentView();
        if(Environment.getInstance().Height <= 100) {
            view = LayoutInflater.from(activity).inflate(R.layout.h_f_set1fg, null);
        }else {
            view = LayoutInflater.from(activity).inflate(R.layout.v_f_set1fg, null);
        }
    }

    @Override
    protected void initControls() {
        super.initControls();
        isEsit = view.findViewById(R.id.btn2);
        spinner = view.findViewById(R.id.drop_down_list_view);
        editText = view.findViewById(R.id.host1);
        bind = view.findViewById(R.id.bind);
        url = view.findViewById(R.id.host3);
        scanVerify = view.findViewById(R.id.host4);
        editText.setText(Env.getAppContext().host);
        url.setText(Env.getAppContext().scanFaceUrl);
        scanVerify.setText(Env.getAppContext().scanVerify+"");
        textView = view.findViewById(R.id.className);
        openScantrue = view.findViewById(R.id.openScantrue);
        openScanSlideSwitch = view.findViewById(R.id.openScanSlideSwitch);
        time = view.findViewById(R.id.EdbackMain);
        time.setText(Env.getAppContext().backMainTime+"");
        if(Environment.getInstance().Height <= 100 ) {
            try {
                setSwitchCheckedState();
                openScanSlideSwitch.setSlideListener(openScanSlideSwitchListener);
            } catch (Exception e) {
                Env.error(Environment.getInstance().fileUtil.Errorinfo(e));
            }
        }
    }

    @Override
    protected void setListener() {
        super.setListener();
        isEsit.setOnClickListener(this);
        bind.setOnClickListener(this);
    }

    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = activity;

    }

    @Override
    public void onResume() {
        super.onResume();
        if (Env.getAppContext().isInitial) {
            runThreadAction("getAllClass");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        spinner.closePopWindow();
    }

    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);
    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
         super.runThreadActionExceute(actionName);

        if(actionName.equals("getAllClass")){
            return Env.getAppPresenter().getAllClassList();
        }else if(actionName.equals("bindClass")){
            return Env.getAppPresenter().bindBanPai(spinner.selectId,Env.getAppContext().carddevid);
        }
        return  null;
    }

    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);
        if(actionName.equals("getAllClass")){
            getAllClassResponse response = (getAllClassResponse) result;
            if(response.isSuccess()){
                list = response.list;
                spinner.setItemsData(list);
            }else {
                ToastUtil.showToast(activity,response.getErrMsg());
            }

        }else if(actionName.equals("bindClass")){
            bindBanPaiResponse response = (bindBanPaiResponse) result;
            if(response.isSuccess()){
                handler.postDelayed(new Runnable()
                {
                    public void run()
                    {
                        activity.setResult(1);
                        activity.finish();
                    }
                }, 600);

                ToastUtil.showToast(activity, "绑定成功");
            }else {
                ToastUtil.showToast(activity,response.getErrMsg());
            }
        }
    }

    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn2:
                setIsEsit();
                break;
            case R.id.bind:
                runThreadAction("bindClass");
                break;
        }
    }

    private void setIsEsit(){
        if(TextUtils.isEmpty(editText.getText().toString())){
            ToastUtil.showToast(activity,"请输入IP地址");
            return;
        }
        if(editText.getText().toString().trim().contains(" ")){
            ToastUtil.showToast(activity,"IP地址存在空格，请清除");
            return;
        }
        if(TextUtils.isEmpty(time.getText().toString().trim())){
            ToastUtil.showToast(activity,"请输入不操作时限");
            return;
        }
        if (Env.getAppContext().openScan) {

            if (TextUtils.isEmpty(scanVerify.getText().toString())) {
                ToastUtil.showToast(activity, "识别度不能为空");
                return;
            }
//        if(!TextUtils.isEmpty(url.getText().toString())){
//            Pattern pattern = Pattern
//                    .compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
//            if(!pattern.matcher(url.getText().toString()).matches()){
//                ToastUtil.showToast(activity,"刷脸的URL格式错误，请仔细检查！");
//                return;
//            }
//        }
            int score = (int) Math.floor(Double.parseDouble(scanVerify.getText().toString()));
            Env.getHelper().put("scanVerify",score);
            Env.getHelper().put("scanFaceUrl",url.getText().toString());

        }

        XMLBean xmlBean = new XMLBean();
        xmlBean.setData("");
        xmlBean.setUrl(editText.getText().toString().trim());
        xmlBean.setVersion("1");
        AnalyzeXMLUtil.modifyXml(Env.getAppContext().CONFIGPATH,xmlBean);

        Env.getHelper().put("backMainTime",Integer.parseInt(time.getText().toString()));

        ToastUtil.showToast(activity,"保存成功");
        spinner.closePopWindow();
        try {
            new InitialAppContext(Environment.getInstance()).reinitial();
            new InitialHardware(Environment.getInstance()).reinitial();
            new InitialAppUpdate(Environment.getInstance()).reinitial();
            runThreadAction("getAllClass");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private SlideSwitch.SlideListener openScanSlideSwitchListener = new SlideSwitch.SlideListener() {
        @Override
        public void open() throws Exception {
            openScantrue.setVisibility(View.VISIBLE);
            Env.getAppContext().openScan = true;

            Env.getHelper().put("openScan" ,true);

        }

        @Override
        public void close() throws Exception {
            openScantrue.setVisibility(View.GONE);
            Env.getAppContext().openScan = false;
            Env.getHelper().put("openScan" ,false);

        }
    };

    private void setSwitchCheckedState() throws Exception {
        if (Env.getAppContext().openScan) {
            openScantrue.setVisibility(View.VISIBLE);
            openScanSlideSwitch.setState(true);
        }else {
            openScantrue.setVisibility(View.GONE);
            openScanSlideSwitch.setState(false);
        }
    }


}
